package com.qxsx.midi.activity.me;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.qxsx.midi.R;
import com.qxsx.midi.activity.base.BaseActivity;
import com.qxsx.midi.config.AppContext;
import com.qxsx.midi.utils.AsyncHttpHelper;
import com.qxsx.midi.utils.Base64Coder;
import com.qxsx.midi.utils.CustomProgress;
import com.qxsx.midi.utils.SPUtils;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;

/**
 * Created by Joney on 2015/9/9.
 * 音频申请
 */
public class ApplyMusicActivity extends BaseActivity implements OnClickListener {
    private CustomProgress customProgress;

    private boolean flag = false;
    private boolean flag1 = false;
    private EditText et_name, et_content;
    private LinearLayout ll_nomarl;//未添加封皮
    private ImageView iv_small_img;//缩放图
    private ImageView iv_img; // 整体背景图
    private TextView tv_none;// 是否添加封面
    public static final int REQUSET = 1;
    private String dataIntent = "";//封面图片的Base 字符串
    String srcPath = "";
    private Button btn_send;
    //要上传的图片数据
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int RESULT_REQUEST_CODE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_apply);
        setNavBtn(R.mipmap.back, 0);
        setTitle("音频申请");
        findById();

        inItData();
    }


    private void findById() {
        btn_send = (Button) findViewById(R.id.btn_send);
        btn_send.setOnClickListener(this);
        ll_nomarl = (LinearLayout) findViewById(R.id.ll_nomarl);
        iv_small_img = (ImageView) findViewById(R.id.iv_small_img);
        iv_img = (ImageView) findViewById(R.id.iv_img);
        tv_none = (TextView) findViewById(R.id.tv_none);
        et_name = (EditText) findViewById(R.id.et_name);
        et_content = (EditText) findViewById(R.id.et_content);

        ll_nomarl.setOnClickListener(this);
        iv_small_img.setOnClickListener(this);
    }


    private void inItData() {

    }


    @Override
    protected void HandleTitleBarEvent(TitleBar component, View v) {
        switch (component) {
            case LEFT:
                finish();
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        flag = false;
        flag1 = false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_nomarl:
                Intent intent = new Intent();
                intent.setClass(AppContext.getContext(), ApplyMusicSelectActivity.class);
                startActivityForResult(intent, REQUSET);
                break;

            case R.id.iv_small_img:
                if (flag == true) {
                    Intent intent2 = new Intent();
                    intent2.setType("image/*"); // 设置文件类型
                    intent2.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(intent2,
                            IMAGE_REQUEST_CODE);
                } else {
                    ShowToast("Please Choose One Video");
                }

                break;
            case R.id.btn_send:
                Apply();
                break;
            default:

                break;


        }
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param data
     */
    @SuppressWarnings("deprecation")
    private void getImageToView(Intent data) {
        Bundle extras = data.getExtras();
        ByteArrayOutputStream stream = null;
        Bitmap photo = null;
        Drawable drawable = null;
        String picStr = null;
        byte[] bytes = null;
        if (extras != null) {

            photo = extras.getParcelable("data");
            drawable = new BitmapDrawable(photo);
            ll_nomarl.setVisibility(View.GONE);
            iv_img.setVisibility(View.VISIBLE);

            iv_small_img.setImageDrawable(drawable);
            iv_img.setImageDrawable(drawable);
            tv_none.setText("已添加封面");
            flag1 = true;
            stream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.JPEG, 60, stream);
            bytes = stream.toByteArray();
            // 将图片流以字符串形式存储下来
            picStr = new String(Base64Coder.encodeLines(bytes));
            dataIntent = picStr;
            Log.e("photoStreamAAA", dataIntent);

        }

    }


    private boolean chooes() {
        if (!flag1) {
            ShowToast("请添加音频封皮");
            return false;
        }
        if (et_name.getText().toString().trim().equals("")) {
            ShowToast("请输入音频名称");
            return false;
        }
        if (et_content.getText().toString().trim().equals("")) {
            ShowToast("请输入音频介绍");
            return false;
        }

        return true;
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("return-data", true);
        startActivityForResult(intent, RESULT_REQUEST_CODE);
    }

    /**
     * 音频上传
     */
    private void Apply() {


        if (TextUtils.isEmpty(et_name.getText().toString().trim())) {
            Toast.makeText(ApplyMusicActivity.this, "名称不能为空！", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(et_content.getText().toString().trim())) {
            Toast.makeText(ApplyMusicActivity.this, "描述不能为空！", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(dataIntent.trim())) {
            Toast.makeText(ApplyMusicActivity.this, "封面还未设置，请您设置封面！", Toast.LENGTH_SHORT).show();
            return;
        }


        //服务器端地址
        String url = "http://121.40.139.86/VInterface/processCoustom";
        String user_id = (String) SPUtils.get(AppContext.getContext(), "user_id", "");
        RequestParams param = new RequestParams();
        try {
            param.put("show_content_url", new File(srcPath));
            param.put("user_id", user_id);
            param.put("show_name", et_name.getText().toString().trim());
            param.put("show_reamk", et_content.getText().toString().trim());
            param.put("show_cove_url", dataIntent);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(ApplyMusicActivity.this, "文件不存在！", Toast.LENGTH_LONG).show();
        }


        final ProgressDialog pd = new ProgressDialog(ApplyMusicActivity.this);

        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        pd.setMessage("Uploading Music...");

        pd.setCancelable(false);


        AsyncHttpHelper.postAbsoluteUrl(url, param, new TextHttpResponseHandler() {


            @Override
            public void onStart() {
                super.onStart();
                pd.show();
            }

            @Override
            public void onSuccess(int arg0, Header[] arg1, String arg2) {
                Toast.makeText(ApplyMusicActivity.this, "音频申请成功！", Toast.LENGTH_LONG).show();
                pd.dismiss();
                finish();
            }


            @Override
            public void onFailure(int arg0, Header[] arg1, String arg2, Throwable t) {
                Toast.makeText(ApplyMusicActivity.this, "音频申请失败！", Toast.LENGTH_LONG).show();
            }


            @Override
            public void onProgress(int bytesWritten, int totalSize) {
                super.onProgress(bytesWritten, totalSize);
                pd.setProgress((int) ((bytesWritten / (float) totalSize) * 100));
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_CANCELED) {

            if (resultCode != RESULT_CANCELED) {

                switch (requestCode) {
                    case IMAGE_REQUEST_CODE:
                        startPhotoZoom(data.getData());

                        break;
                    case RESULT_REQUEST_CODE:
                        if (data != null) {
                            getImageToView(data);
                        }
                        break;
                }

            }

        }

        if (requestCode == ApplyMusicActivity.REQUSET && resultCode == RESULT_OK) {
            srcPath = data.getStringExtra(ApplyMusicSelectActivity.KEY_YINPIN_PATH);
            Log.w("srcPath", srcPath);
            if (srcPath != "") {
                flag = true;
            }
        }

    }
}
